# Verify conditions
if [ ! -z $UID ] && [ $UID -ne 0 ]; then
    echo Superuser privileges are required to run this script.
    exit 1
fi

ping -c 1 -W 1 8.8.8.8 > /dev/null 2>&1
if [ $? -ne 0 ]; then
    ping -c 1 -W 1 www.baidu.com > /dev/null 2>&1
    if [ $? -ne 0 ]; then
        echo Network unreachable.
        exit 1
    fi
fi

if [ -d "/usr/share/dotnet" ]; then
    echo .net environment conflicts. Please remove the environments installed by 'apt-get install'.
    exit 1
fi

# Remove files of legacy installation
if [ -d "/opt/dotnet" ]; then
    rm -rf /opt/dotnet
    echo /opt/dotnet removed.
fi

if [ ! -z `cat /etc/environment | grep DOTNET_ROOT=` ]; then
    sed -i '/^DOTNET_ROOT=/d' /etc/environment
    echo /etc/environment reverted.
fi

if [ -f "/etc/profile.d/dotnet-core.sh" ]; then
    rm -f /etc/profile.d/dotnet-core.sh
    echo /etc/profile.d/dotnet-core.sh removed.
fi

if [ -f "/etc/profile.d/dotnet.sh" ]; then
    rm -f /etc/profile.d/dotnet.sh
    echo /etc/profile.d/dotnet.sh removed.
fi


# Remove install lock
rm -f /var/lib/apt/lists/lock
rm -f /var/lib/dpkg/lock
rm -f /var/lib/dpkg/lock-frontend
rm -f /var/cache/apt/archives/lock

apt-get update

# Install .net
if [ ! -d "/usr/share/dotnet-manually-installed/shared/Microsoft.NETCore.App/3.1.7" ]; then
    DOTNETCORE_PACKAGE=dotnet-runtime-3.1.7-linux-arm64.tar.gz
    if [ ! -f $DOTNETCORE_PACKAGE ]; then
        echo $DOTNETCORE_PACKAGE not found.
        exit 1
    fi

    mkdir -p /usr/share/dotnet-manually-installed
    tar zxvf $DOTNETCORE_PACKAGE -C /usr/share/dotnet-manually-installed
    chmod 777 -R /usr/share/dotnet-manually-installed

    apt-get install -y libc6 libgcc1 libgssapi-krb5-2 libicu55 libssl1.0.0 libstdc++6 zlib1g libgdiplus
fi

PATH_ROW_SRC=`cat /etc/environment | grep PATH=\\"`
if [ ! -z "$PATH_ROW_SRC" ]; then
    PATH_ROW_TEMP=${PATH_ROW_SRC/"/usr/share/dotnet-manually-installed:"/}
    PATH_ROW_DST=${PATH_ROW_TEMP/"PATH=\""/"PATH=\"/usr/share/dotnet-manually-installed:"}
    sed -i "s|$PATH_ROW_SRC|$PATH_ROW_DST|g" /etc/environment
fi

if [ -z `cat /etc/environment | grep DOTNET_ROOT=` ]; then
    echo 'DOTNET_ROOT=/usr/share/dotnet-manually-installed' | tee -a /etc/environment
fi

# Install other software
apt-get install -y libsqlite3-0 libwebkit2gtk-3.0-25

echo Done.
